import React, { useEffect, useRef, useState } from 'react';
import {
  Form,
  Input,
  Modal,
  Select,
  Row,
  Col,
  DatePicker,
  message,
  InputNumber,
} from 'antd';
import { adminCompanyType, adminPriceType, payMethod } from '@/utils/constant';
import { useRequest, useUpdateEffect } from '@umijs/hooks';
import {
  apiProductGetList,
  apiPurchaseCommodityGetList,
  apiPurchaseGetList,
  apiPurchaseSupplierGetList,
} from '@/services/otherServices';
import { uniqBy } from '@/utils/utils';

const FormItem = Form.Item;
const Detail = (props: any) => {
  const {
    visible,
    onCancel,
    onOk,
    getForm,
    loading,
    afterClose,
    editId,
  } = props;
  const [form] = Form.useForm();
  const [searchValue, setSearchValue] = useState('');
  const [data, setData] = useState([]);
  const [selectData, setSelectData] = useState([]);
  const [selectData2, setSelectData2] = useState([]);
  const [materialType, setMaterialType] = useState(undefined);
  const [productName, setProductName] = useState(undefined);
  const [model, setModel] = useState(undefined);

  const [productNameValue, setProductNameValue] = useState('');
  const [modelValue, setModalValue] = useState('');

  const [supplierValue, setSupplierValue] = useState('');
  const [supplierData, setSupplierData] = useState([]);

  const { loading: getListLoading, run } = useRequest(apiPurchaseGetList, {
    manual: true,
    throttleInterval: 500,
    onSuccess: (res, params) => {
      setData(res.data);
    },
  });

  const { loading: supplierLoading, run: getsupplier } = useRequest(
    apiPurchaseSupplierGetList,
    {
      manual: true,
      debounceInterval: 500,
      onSuccess: (res, params) => {
        setSupplierData(res.data);
      },
    },
  );

  const { loading: pageLoading, run: getPage } = useRequest(
    apiPurchaseCommodityGetList,
    {
      manual: true,
      debounceInterval: 500,
      onSuccess: (res, params) => {
        const arr: any = uniqBy(res.data, 'productName');
        setSelectData(arr);
      },
    },
  );

  const { loading: pageLoading2, run: getPage2 } = useRequest(
    apiPurchaseCommodityGetList,
    {
      manual: true,
      debounceInterval: 500,
      onSuccess: (res, params) => {
        res.data.forEach((n: any) => {
          if (n.model === '') {
            n.model = ' ';
          }
        });
        setSelectData2(res.data);
      },
    },
  );

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
      md: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
      md: { span: 18 },
    },
  };

  useUpdateEffect(() => {
    run({
      productName: searchValue,
      pageNo: 1,
      pageSize: 10,
    });
  }, [searchValue]);

  useUpdateEffect(() => {
    getsupplier({
      supplier: supplierValue,
      pageNo: 1,
      pageSize: 10,
    });
  }, [supplierValue]);

  useEffect(() => {
    run({
      pageNo: 1,
      pageSize: 10,
    });
    getForm(form);
  }, []);
  useUpdateEffect(() => {
    if (visible === true) {
      run({
        pageNo: 1,
        pageSize: 10,
      });
      getsupplier({
        pageNo: 1,
        pageSize: 10,
      });
    }
  }, [visible]);

  useUpdateEffect(() => {
    if (visible === true && editId !== undefined) {
      if (form.getFieldValue('materialType') !== undefined) {
        getPage({
          materialType: form.getFieldValue('materialType'),
          pageNo: 1,
          pageSize: 200,
        });
      }

      if (form.getFieldValue('productName') !== undefined) {
        getPage2({
          productName: form.getFieldValue('productName'),
          materialType: form.getFieldValue('materialType'),
          pageNo: 1,
          pageSize: 200,
        });
      }
      if (
        form.getFieldValue('model') !== undefined &&
        form.getFieldValue('model') === ''
      ) {
        form.setFieldsValue({
          model: ' ',
        });
      }
    }
  }, [visible, editId]);

  useUpdateEffect(() => {
    if (materialType === '' || materialType === undefined) {
      message.destroy();
      message.error('请先选择分类');
      return;
    }
    getPage({
      productName: productNameValue,
      materialType,
      pageNo: 1,
      pageSize: 200,
    });
  }, [productNameValue]);

  useUpdateEffect(() => {
    if (productName === '' || productName === undefined) {
      message.destroy();
      message.error('请先选择品名');
      return;
    }
    getPage2({
      model: modelValue,
      productName: productName,
      materialType,
      pageNo: 1,
      pageSize: 200,
    });
  }, [modelValue]);

  const onValuesChange = (changedValues: any, allValues: any) => {
    if (changedValues.purchaseAmount && allValues.price) {
      form.setFieldsValue({
        totalAmount: changedValues.purchaseAmount * allValues.price,
      });
    }
    if (changedValues.price && allValues.purchaseAmount) {
      form.setFieldsValue({
        totalAmount: allValues.purchaseAmount * changedValues.price,
      });
    }

    if (changedValues.materialType) {
      form.setFieldsValue({
        productName: undefined,
        model: undefined,
      });
      setMaterialType(changedValues.materialType);
      setSelectData2([]);
      getPage({
        pageNo: 1,
        pageSize: 200,
        materialType: changedValues.materialType,
      });
    }
    if (changedValues.productName) {
      form.setFieldsValue({
        model: undefined,
      });
      setProductName(changedValues.productName);
      getPage2({
        pageNo: 1,
        pageSize: 200,
        materialType: materialType,
        productName: changedValues.productName,
      });
    }
    if (changedValues.model) {
      const result: any = selectData2.filter(
        (n: any) => n.model === changedValues.model,
      );
      setModel(changedValues.model);
      form.setFieldsValue({
        commodityId: result[0]?.id,
      });
    }
  };

  return (
    <Modal
      width={1024}
      afterClose={afterClose}
      destroyOnClose={true}
      confirmLoading={loading}
      title={editId !== undefined ? '编辑' : '新增'}
      visible={visible}
      onCancel={onCancel}
      onOk={onOk}
    >
      <Form
        hideRequiredMark
        style={{ marginTop: 8 }}
        form={form}
        name="basic"
        onValuesChange={onValuesChange}
      >
        <Row>
          <Col span={12} style={{ display: 'none' }}>
            <FormItem
              rules={[{ required: true, message: '请输入商品 id' }]}
              {...formItemLayout}
              label={'商品 id'}
              name="commodityId"
            >
              <Input />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              {...formItemLayout}
              rules={[{ required: true, message: '请选择分公司' }]}
              label={'分公司'}
              name="company"
            >
              <Select>
                {adminCompanyType.map(item => (
                  <Select.Option key={item.value} value={item.value}>
                    {item.label}
                  </Select.Option>
                ))}
              </Select>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请选择分类' }]}
              {...formItemLayout}
              label={'分类'}
              name="materialType"
            >
              <Select>
                <Select.Option value={'原料'}>原料</Select.Option>
                <Select.Option value={'边料'}>边料</Select.Option>
                <Select.Option value={'化工'}>化工</Select.Option>
                <Select.Option value={'配件'}>配件</Select.Option>
              </Select>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请选择品名' }]}
              {...formItemLayout}
              label={'品名'}
              name="productName"
            >
              <Select
                showSearch
                onSearch={value => {
                  setProductNameValue(value);
                }}
                filterOption={false}
                placeholder="请选择品名"
              >
                {selectData &&
                  selectData.map((item: any) => (
                    <Select.Option key={item.id} value={item.productName}>
                      {item.productName}
                    </Select.Option>
                  ))}
              </Select>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              {...formItemLayout}
              label={'型号'}
              name="model"
              rules={[{ required: true, message: '请选择型号' }]}
            >
              <Select
                showSearch
                onSearch={value => {
                  setModalValue(value);
                }}
                filterOption={false}
                placeholder="请选择型号"
              >
                {selectData2 &&
                  selectData2.map((item: any) => (
                    <Select.Option key={item.id} value={item.model}>
                      {item.model}
                    </Select.Option>
                  ))}
              </Select>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请输入供应商' }]}
              {...formItemLayout}
              label={'供应商'}
              name="supplier"
            >
              <Select
                showSearch
                onSearch={value => {
                  setSupplierValue(value);
                }}
                filterOption={false}
                placeholder="请选择供应商"
              >
                {supplierData &&
                  supplierData.map((item: any) => (
                    <Select.Option key={item.id} value={item.supplier}>
                      {item.supplier}
                    </Select.Option>
                  ))}
              </Select>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请输入采购数量' }]}
              {...formItemLayout}
              label={'采购数量'}
              name="purchaseAmount"
            >
              <InputNumber style={{ width: '100%' }} />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请输入单位' }]}
              {...formItemLayout}
              label={'单位'}
              name="unit"
            >
              <Input />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem {...formItemLayout} label={'单价'} style={{ margin: 0 }}>
              <Input.Group compact>
                <FormItem
                  rules={[{ required: true, message: '请选择单价' }]}
                  style={{ width: '40%' }}
                  name="priceType"
                >
                  <Select style={{ width: '100%' }}>
                    {adminPriceType.map(item => (
                      <Select.Option key={item.value} value={item.value}>
                        {item.label}
                      </Select.Option>
                    ))}
                  </Select>
                </FormItem>
                <FormItem
                  rules={[{ required: true, message: '请输入价格' }]}
                  style={{ width: '60%' }}
                  name={'price'}
                >
                  <InputNumber style={{ width: '100%' }} placeholder={'价格'} />
                </FormItem>
              </Input.Group>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem {...formItemLayout} label={'总金额'} name="totalAmount">
              <InputNumber disabled={true} style={{ width: '100%' }} />
            </FormItem>
          </Col>
          {editId && (
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label={'已付金额'}
                name="payedAmount"
              >
                <InputNumber disabled={true} style={{ width: '100%' }} />
              </FormItem>
            </Col>
          )}
          {editId && (
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label={'未付金额'}
                name="unpayAmount"
              >
                <InputNumber disabled={true} style={{ width: '100%' }} />
              </FormItem>
            </Col>
          )}
          {editId && (
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label={'已到票金额'}
                name="receivedInvoiceAmount"
              >
                <InputNumber disabled={true} style={{ width: '100%' }} />
              </FormItem>
            </Col>
          )}
          {editId && (
            <Col span={12}>
              <FormItem
                {...formItemLayout}
                label={'未到票金额'}
                name="unreceivedInvoiceAmount"
              >
                <InputNumber disabled={true} style={{ width: '100%' }} />
              </FormItem>
            </Col>
          )}
          <Col span={12}>
            <FormItem
              {...formItemLayout}
              label={'结算方式'}
              name="settlementMethod"
              rules={[{ required: false, message: '请输入结算方式' }]}
            >
              <Select>
                {payMethod.map(item => (
                  <Select.Option key={item.value} value={item.value}>
                    {item.label}
                  </Select.Option>
                ))}
              </Select>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请输入采购人员' }]}
              {...formItemLayout}
              label={'采购人员'}
              name="purchaser"
            >
              <Input />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem {...formItemLayout} label={'备注'} name="remark">
              <Input.TextArea rows={3} />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
export default Detail;
